import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api';
//shopCart模块小仓库
const state = {
  cartList: []
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  //获取购物车列表数据
  async getCartList({ commit }) {
    const result = await reqCartList()
    if (result.code == 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  //删除购物车商品
  async deleteCartLIstBySkuId({ commit }, skuId) {
    const result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return 'ok'
    }
    else {
      return Promise.reject(new Error('faile'))
    }
  },
  //修改购物车选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    const result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    }
    else {
      return Promise.reject(new Error('faile'))
    }
  },
  //删除勾选的商品
  deleteAllCheckedCart({ dispatch, getters }) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      let promise = (item.isChecked == 1) ? dispatch('deleteCartLIstBySkuId', item.skuId) : ''
      PromiseAll.push(promise)
    });
    //全部成功返回成功，
    //一个错误，返回错误console.log(PromiseAll);
    return Promise.all(PromiseAll)
  },
  //修改全部产品的状态
  updateAllCartIsChecked({ dispatch, state }, isChecked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  }
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}